package top.mcwebsite.playandroid.common.network.impl.cookie

import okhttp3.Cookie
import java.io.ObjectInputStream
import java.io.ObjectOutputStream
import java.io.Serializable

class SerializableCookie(
    @Transient private val cookie: Cookie,
) : Serializable {

    private var clientCookie: Cookie? = null

    fun getCookie(): Cookie = clientCookie ?: cookie

    private fun writeObject(out: ObjectOutputStream) {
        out.writeObject(this.cookie.name())
        out.writeObject(this.cookie.value())
        out.writeLong(this.cookie.expiresAt())
        out.writeObject(this.cookie.domain())
        out.writeObject(this.cookie.path())
        out.writeBoolean(this.cookie.secure())
        out.writeBoolean(this.cookie.httpOnly())
        out.writeBoolean(this.cookie.hostOnly())
        out.writeBoolean(this.cookie.persistent())
    }

    private fun readObject(`in`: ObjectInputStream) {
        val name = `in`.readObject() as String
        val value = `in`.readObject() as String
        val expiresAt = `in`.readLong()
        val domain = `in`.readObject() as String
        val path = `in`.readObject() as String
        val secure = `in`.readBoolean()
        val httpOnly = `in`.readBoolean()
        val hostOnly = `in`.readBoolean()
        val persistent = `in`.readBoolean()

        var builder = Cookie.Builder()
            .name(name)
            .value(value)
            .expiresAt(expiresAt)
            .path(path)
        builder = if (hostOnly) {
            builder.hostOnlyDomain(domain)
        } else {
            builder.domain(domain)
        }
        builder = if (secure) {
            builder.secure()
        } else {
            builder
        }
        builder = if (httpOnly) {
            builder.httpOnly()
        } else builder
        this.clientCookie = builder.build()
    }
}